/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rest.server;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.common.JSONSerializer;
import io.iec.edp.caf.commons.OldBridge;
import io.iec.edp.caf.commons.core.SerializerFactory;
import io.iec.edp.caf.commons.core.api.DataSerializer;
import io.iec.edp.caf.commons.core.enums.SerializeType;
import io.iec.edp.caf.rest.api.exception.RESTServiceExceptionMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.ext.logging.LoggingFeature;
import org.apache.cxf.feature.Feature;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.message.Message;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangyandong
 */
@Slf4j
public class RESTEndpointUtil {

    @SneakyThrows
    public static Server createJAXRSServer(String address, Bus bus, List<Object> beans) {
        Server server = null;
        try{
            server = createJAXRSServerWithInterceptor(address, bus, beans, null);
//            logApi(address,"restapi.txt",true,false);
        }catch (Throwable e){
            log.error("注册rest服务出错，path:"+address+"，原因"+e.getMessage(),e);
        }finally {
            return server;
        }
    }

    @SneakyThrows
    public static Server createJAXRSServerWithInterceptor(String address, Bus bus, List<Object> beans, List<Interceptor<? extends Message>> interceptors) {
        JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
        endpoint.setAddress(address);
        endpoint.setBus(bus);
        endpoint.setServiceBeans(beans);
        endpoint.setFeatures(new ArrayList<Feature>() {
            {
                this.add(buildLoggingFeature());
            }
        });

        DataSerializer serializer = SerializerFactory.getSerializer(SerializeType.Json);

        endpoint.setProviders(new ArrayList<Object>() {
            {
                this.add(new JacksonJsonProvider((ObjectMapper) serializer.getObjectMapper()));
                this.add(new RESTServiceExceptionMapper());
            }
        });

        if(interceptors!=null && interceptors.size()>0){
            endpoint.getInInterceptors().addAll(interceptors);
        }

        return endpoint.create();
    }

    private static LoggingFeature buildLoggingFeature() {
        return new LoggingFeature();
    }

    public static void logApi(Object data,String filename,boolean append,boolean isNewLine) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    if(data!=null){
                        var root = CAFContext.current.getRuntimePath();
                        String fileFullPath = root+"/"+filename;
                        var index = fileFullPath.lastIndexOf("/");
                        String dirFullPath = fileFullPath.substring(0,index);


                        File dataFile =new File(fileFullPath);
                        File dirFile = new File(dirFullPath);

                        if (!dirFile.exists()) {
                            dirFile.mkdirs();
                        }

                        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dataFile,append), "UTF-8"));
                        out.write((String)data);
                        out.write("\r\n");  //换行
                        if(isNewLine){
                            out.write("\r\n");
                        }
                        out.close();
                    }

                }
                catch(Exception e){
                    log.error("打印日志出错",e);
                }
            }
        }).start();
    }

}
